package com.lge.clock.alarmclock;

import static com.lge.clock.timer.Timers.TIMER_OFF_TAG;
import static com.lge.clock.util.CommonUtil.getDefaultRingToneInfo;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.content.res.Resources;
import android.database.Cursor;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
// [suhyun99.kim][IN][KU5400][48538] 2011.08.31. Memo longclick issue fix 
import android.view.View.OnLongClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.lge.clock.R;
import com.lge.clock.util.CommonUtil;
import com.lge.clock.util.MediaInfoHolder;
import com.lge.clock.util.CommonUtil.AlarmDBQueryCondition;
import com.lge.clock.util.CommonUtil.OPERATOR;
import com.lge.clock.util.CommonUtil.PrefreParent;
import com.lge.clock.util.MediaInfoHolder.MediaLocation;
import com.lge.clock.util.Log;
import com.lge.lgdrm.Drm;
import com.lge.sui.widget.control.SUIDrumTimePicker;
import com.lge.sui.widget.control.SUIDrumTimePicker.OnTimeChangedListener;
import com.lge.sui.widget.control.SUIToggleButtonGroup;//
/* LGSI_CHANGE_S: Alarm
 * 2012.04.13,prajna.dalei@lge.com,
 * Number conversion in Alarm settings
 */
import java.util.Locale;
/* LGSI_CHANGE_E: Alarm*/
import android.view.*;

/* I3.0 Volume Control Code [START] */
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import java.io.IOException;
import android.drm.DrmManagerClient;
import java.io.IOException;
/* I3.0 Volume Control Code [END] */

/**
 *
 * @author donggeun.kim
 *
 */
public class ALSettings extends Activity implements OnClickListener, TextWatcher 
{ 
	private static final String TAG = "ALSettings";
	private Button mSaveButton;
	private Button mCancelButton;    
	private AlertDialog.Builder  snoozeDialog ;
	/**
	 * 2012.03.09 suein1209.kim
	 */
	private AlertDialog.Builder alarmToneDialog;
	
	private Intent ringtonePickerIntent = null; // added by essin@lge.com 2010.12.06
	private boolean mShowDefault;
	private boolean mShowSilent;
	
	/* [START] 2012.03.09 suein1209.kim */
	/**
	 * Alarm tone request code numb3r
	 */
	private final int mAlarmToneRqCode = 107;
	
	/**
	 * Alarm tone request code numb3r
	 */
	private final int mMusicRqCode = 108;
	
	/* [END] 2012.03.09 suein1209.kim */
    
	private BroadcastReceiver mSDCardMountEventReceiver = null;
	private static int sToastTextForEmmc = 0;
	/**
	 * Field settingHaving.
	 */
	public static HashMap<String, String> settingHaving = new HashMap<String, String>();
	/**
	 * Field yoil.
	 */
	public static final int[] yoil = { 0,0,0, 0,0,0,0 };
	 
	// [1] Snooze
	private LinearLayout snoozeTopGroup;   	
	private LinearLayout toneTopGroup;
	private LinearLayout vibTopGroup;
	private LinearLayout puzzleTopGroup;
	
	/* I3.0 Volume Control Code [START] */
	private LinearLayout volume_TopGroup;
	/* I3.0 Volume Control Code [END] */
	 
	private TextView snoozeWriting;   	
	private TextView toneWriting;  
	private TextView puzzle_main;

	private CheckedTextView vibYN, puzzleYN;
	private EditText memoInput;
	private ContentResolver resolver;
	private Resources res;
	
	//private boolean checkKoreaYN = false;
	
	private SUIDrumTimePicker mTimePicker = null;
    
	private int mIntHour;
	private int mIntMinutes;
	private static int memoLength = 0;
	private boolean create_checker = true;
	private static String initialSnooze;
	private static String initialUri;
	private static String initialVib;
	private static String initialPuzzle;
	private static String initialMemo;
	
/* I3.0 Volume Control Code [START] */
	private boolean isUseVolumeContorl = false;
	private SeekBar alarm_volume_bar;
	private AudioManager audioManager;
	private static String initialAlarmVolume;
	private MediaPlayer mp= new MediaPlayer();
 	int ringerModeStreamTypes; 
 	int ALARM_STREAM_TYPE_BIT;
	private int maxVolume;
	private int currentVolume ;	 
	private int resetVolume;
	
    private String mTone;
    private Context context;
/* I3.0 Volume Control Code [END] */
	
	private static String initialHour;
	private static String initialMinutes;
	private static int initialDaysofweek;
	private String puzzle_value;
	private String puzzle_comvalue;
	
	private InputMethodManager mImm = null;
	private boolean bAlarmSaved = false;
	private String mAlalrmID;
	private Toast memoFullToast;
	
	/**
	 * 2012.02.06 suein1209.kim
	 * Memo area max length = 500;
	 */
	private static final int MEMO_MAX_LENGTH = 500;
	
	boolean mPausedState = false;
	boolean bFinish = false;
	/**
	 * Method init.
	 */
	public void init() {
		bFinish = false;
		/////////////////////////////////////////////////////////////
		mSaveButton   = (Button)findViewById(R.id.saveButton);
		mCancelButton = (Button)findViewById(R.id.cancelButton);
		
		mSaveButton.setOnClickListener(this);
		mCancelButton.setOnClickListener(this);

		// 0) Time
		boolean is24HourFormatType = DateFormat.is24HourFormat(this);
		String hourStr = settingHaving.get("hour");
		String minutes = settingHaving.get("minutes");
		
		final View timer_parent_12 = (View)findViewById(R.id.timer_parent_12);
		final View timer_parent_24 = (View)findViewById(R.id.timer_parent_24);
		
		if(is24HourFormatType) {
			timer_parent_12.setVisibility(View.GONE);
			timer_parent_24.setVisibility(View.VISIBLE);
//			mTimePicker = (SUITimePicker)findViewById(R.id.timepicker_24);
//			mTimePicker.setIs24HourView(true);
			mTimePicker = (SUIDrumTimePicker)findViewById(R.id.timepicker_24);
			mTimePicker.setTimeFormat(SUIDrumTimePicker.TIMEFORMAT_24_HHMM);
		} else {
			timer_parent_12.setVisibility(View.VISIBLE);
			timer_parent_24.setVisibility(View.GONE);
//			mTimePicker = (SUITimePicker)findViewById(R.id.timepicker_12);
//			mTimePicker.setIs24HourView(false);
			mTimePicker = (SUIDrumTimePicker)findViewById(R.id.timepicker_12);
			mTimePicker.setTimeFormat(SUIDrumTimePicker.TIMEFORMAT_12_AMPM);
		}
		
		mIntHour = Integer.parseInt(hourStr);
		mIntMinutes = Integer.parseInt(minutes);
		
		mTimePicker.setCurrentHour(mIntHour);
		mTimePicker.setCurrentMinute(mIntMinutes);
		
//		mTimePicker.refresh();
		mTimePicker.setOnTimeChangedListener(new OnTimeChangedListener() {
			public void onTimeChanged(SUIDrumTimePicker view, int hour, int minute) {	
				setTimeAlarm(hour, minute);
				if(!mPausedState)
					mTimePicker.requestFocus();
			}
		});

		
		// 1) Snooze
		////////////////////////////////////////////////////////////////////////////////////////
		snoozeTopGroup = (LinearLayout)findViewById(R.id.Snooze_TopGroup);
		snoozeWriting  = (TextView)findViewById(R.id.snooze_sub);
		 
		snoozeTopGroup.setOnClickListener(this);
		
		///////////////////////////////////////////////////////////////
		// 2) Tone
		////////////////////////////////////////////////////////////////////////////////////////
		toneTopGroup = (LinearLayout)findViewById(R.id.Tone_TopGroup);
		toneWriting  = (TextView)findViewById(R.id.tone_sub);
		
		toneTopGroup.setOnClickListener(this);
		
		///////////////////////////////////////////////////////////////
		// 3) Vib
		///////////////////////////////////////////////////////////////
		vibTopGroup = (LinearLayout)findViewById(R.id.vib_TopGroup);
		vibTopGroup.setOnClickListener(this);
		  
        vibYN = (CheckedTextView)findViewById(R.id.vibCheckbox);

        ///////////////////////////////////////////////////////////////
        // 4) Puzzle
        ///////////////////////////////////////////////////////////////
        puzzleTopGroup = (LinearLayout)findViewById(R.id.puzzle_TopGroup);
        puzzleTopGroup.setOnClickListener(this);
		puzzle_main = (TextView) findViewById(R.id.puzzle_main);
		//WBT fix td 207874
		if (puzzle_main != null) {
			puzzle_main.setSelected(true);
		}
		  
		puzzleYN = (CheckedTextView)findViewById(R.id.puzzleCheckbox);
         
		///////////////////////////////////////////////////////////////
		// 5) Memo
		///////////////////////////////////////////////////////////////
		memoInput = (EditText)findViewById(R.id.memo_input);
		memoInput.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				
				event_memoTopGroup();
				
				status_text_input_mode = true;
//				memoInput.addTextChangedListener(new TextWatcher()
//				{
//					public void afterTextChanged(Editable arg0) {}
//					public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3) {}
//					public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) 
//					{
//						status_text_input_mode = true;
//						
//					}					
//				});
			}
			
		});
		
		/*[START] 2012.02.06 suein1209.kim add popup the toast when max length*/
		memoInput.addTextChangedListener(this);
		/*[END] 2012.02.06 suein1209.kim add popup the toast when max length*/
		
		//[hyunyong.sim] TD : 77288 when Gesture start do not hide KeyPad [Medic 1513]
		memoInput.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if(!hasFocus){
					memoInput.setFocusable(false);
	                status_text_input_mode = false;
					hideSoftKeyboard();
				}
			}
		});
		
		// [suhyun99.kim][IN][KU5400][48538] 2011.08.31. Memo longclick issue fix START
		memoInput.setOnLongClickListener(new OnLongClickListener() {
			public boolean onLongClick(View v) {
				memoInput.setFocusableInTouchMode(true); 
				memoInput.setFocusable(true);
				memoInput.requestFocus();
				mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				status_text_input_mode = true;
			return false;
			}
		});
		
		// [suhyun99.kim][IN][KU5400][48538] 2011.08.31. Memo longclick issue fix END
        ///////////////////////////////////////////////////////////////
        // 6) ToggleButton
        /////////////////////////////////////////////////////////////
		//BASICPKG_S AlarmClock [sungtan.back@lge.com 110406] Empty ClickListener for ToggleButton Audiable selection #TD 757
		View.OnClickListener toggleClickListener = new View.OnClickListener() {
			
			public void onClick(View v) {
				
			}
		};
		
		int nToggleViews[] = { R.id.toggle_button_mo, R.id.toggle_button_tu, R.id.toggle_button_we, R.id.toggle_button_th,
								R.id.toggle_button_fr, R.id.toggle_button_sa, R.id.toggle_button_su };
		
		ToggleButton toggleBtn = null;
		for ( int nToggleView : nToggleViews ) {
			toggleBtn = (ToggleButton)(findViewById(nToggleView));
			if ( toggleBtn != null ) {
				toggleBtn.setOnClickListener(toggleClickListener);
			}
		}
	}
	
	private SUIToggleButtonGroup tbLayout;
	private boolean status_text_input_mode = false;
	private void event_snoozeTopGroup() 
	{
		/*2012.01.27 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #126293*/
		hideSoftKeyboard();
		
		// [minjoong.park][1443] 2011.10.17. START
    	if(CommonUtil.STOP_DIALOG_REDUNDANCY){
    		CommonUtil.STOP_DIALOG_REDUNDANCY = false;
    	}else{
    		return;
    	}//End of if
    	// [minjoong.park][1443] 2011.10.17. END
		
		final CharSequence[] snooze_kinds = res.getTextArray(R.array.STR_Clock_SELECTSNOOZEKINDS_NORMAL);

		if (snoozeDialog == null) {
			snoozeDialog = new AlertDialog.Builder(this);  	
			snoozeDialog
			.setTitle(R.string.alarm_setting_snooze)    //[yeonju7.kim][IN][SDQ_11][P940][5894] 2011.08.29
			.setOnCancelListener(new OnCancelListener() { 
				public void onCancel(DialogInterface dialog) { 
						if(snoozeDialog != null) {
							// [minjoong.park][1443] 2011.10.17. START
							CommonUtil.STOP_DIALOG_REDUNDANCY = true;
							// [minjoong.park][1443] 2011.10.17. END
							snoozeDialog = null;
						}
				}
			})
			.setNeutralButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					
				    // [minjoong.park][1443] 2011.10.17. START
					CommonUtil.STOP_DIALOG_REDUNDANCY = true;
					// [minjoong.park][1443] 2011.10.17. END
					
					snoozeDialog = null;
				}
			})   
			.setSingleChoiceItems(R.array.STR_Clock_SELECTSNOOZEKINDS_NORMAL, getSnoozeIndex(), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					
				    // [minjoong.park][1443] 2011.10.17. START
					CommonUtil.STOP_DIALOG_REDUNDANCY = true;
					// [minjoong.park][1443] 2011.10.17. END
					
					if(0 == which) {
						snoozeWriting.setText( snooze_kinds[which] );
						settingHaving.put("snooze", "0");
					} else if (1 == which) {
						snoozeWriting.setText( snooze_kinds[which] );
						settingHaving.put("snooze", "5");
					} else if (2 == which) {
						snoozeWriting.setText( snooze_kinds[which] );
						settingHaving.put("snooze", "10");			
					} else if (3 == which) {
						snoozeWriting.setText( snooze_kinds[which] );
						settingHaving.put("snooze", "15");			
					} else if (4 == which) {
						snoozeWriting.setText( snooze_kinds[which] );
						settingHaving.put("snooze", "20");
					}  else if (5 == which) {
						snoozeWriting.setText( snooze_kinds[which] );
						settingHaving.put("snooze", "25");			   
					} else if (6 == which) {
						snoozeWriting.setText( snooze_kinds[which] );
						settingHaving.put("snooze", "30");
					} else if (7 == which) {
						snoozeWriting.setText( snooze_kinds[which] );
						settingHaving.put("snooze", "60");
					}
					
	            	dialog.cancel(); 
	            	snoozeDialog = null;
				}
			}).show();
		}
	}
	
    private void event_toneTopGroup() {
    	
        // [minjoong.park][1443] 2011.10.17. START
    	if(CommonUtil.STOP_DIALOG_REDUNDANCY){
    		CommonUtil.STOP_DIALOG_REDUNDANCY = false;
    	}else{
    		return;
    	}//End of if
    	// [minjoong.park][1443] 2011.10.17. END
    	
    	/*[START] 2012.03.09 suein1209.kim*/
    	if(CommonUtil.getBuildOperator() == OPERATOR.DCM ){
    		showAlarmToneSelectDialog();
    	}else{
    		startRingToneDialog();
    	} //End Of if
    	/*[END] 2012.03.09 suein1209.kim*/
    }
    /**
     * 2012.03.09 suein1209.kim
     */
    private void showAlarmToneSelectDialog(){
    	/*Exception*/
		if (this.alarmToneDialog != null) return ;
		
		final int IDX_ALARM_TONE = 0;
		final int IDX_MUSIC = 1;
		
    	CharSequence[] alarmTypeList = new CharSequence[2];
    	alarmTypeList[IDX_ALARM_TONE] = this.getResources().getString(R.string.alarm_setting_tone); 
    	alarmTypeList[IDX_MUSIC] = this.getResources().getString(R.string.sp_TXT_Music_SHORT); 
    	
		alarmToneDialog = new AlertDialog.Builder(this);  	
		alarmToneDialog
		.setTitle(R.string.alarm_setting_tone)
		.setOnCancelListener(new OnCancelListener() { 
			public void onCancel(DialogInterface dialog) { 
					if(alarmToneDialog != null) {
						// [minjoong.park][1443] 2011.10.17. START
						CommonUtil.STOP_DIALOG_REDUNDANCY = true;
						// [minjoong.park][1443] 2011.10.17. END
						alarmToneDialog = null;
					}
			}
		}).setNeutralButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				
			    // [minjoong.park][1443] 2011.10.17. START
				CommonUtil.STOP_DIALOG_REDUNDANCY = true;
				// [minjoong.park][1443] 2011.10.17. END
				
				alarmToneDialog = null;
			}
		}).setItems(alarmTypeList, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int typeInd3x) {
				
				switch (typeInd3x) {
				case IDX_ALARM_TONE :
					startRingToneDialog();
					break;
					
				case IDX_MUSIC :
					startMusicActivity();
					break;
					
				default:
					/*DO Nothing*/
					break;
				} //End Of swithc
				
				/*dialog redundancy*/
				CommonUtil.STOP_DIALOG_REDUNDANCY = true;
				alarmToneDialog = null;
			} //End Of switch
		}).show();
		
    } //End Of Method getAlarmToneDialogInstance
    
    /**
     * 2012.03.09 suein1209.kim
     */
    private void startRingToneDialog(){
    	if(ringtonePickerIntent != null) return;
    	
		mShowDefault = false;
		mShowSilent  = true;
		// [taewan.kim][67563] 2011.09.30. Add Null Check START
		Uri findTone = null;
		ringtonePickerIntent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
		String tone	= settingHaving.get("tone");
		if (tone != null){
			findTone = Uri.parse(tone);
		}
		// [taewan.kim][67563] 2011.09.30. Add Null Check END
		if(isSilentMode(tone)){
			findTone = null;
		}
		ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, findTone);
		ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, mShowDefault);
		ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, mShowSilent);
		ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_ALARM);
		ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, this.getResources().getString(R.string.alarm_setting_tone));
		startActivityForResult(ringtonePickerIntent, mAlarmToneRqCode);
      
    } //End Of Method startRingToneDialog
    	
    /**
     * 2012.03.09 suein1209.kim
     */
    private void startMusicActivity(){
    	final Intent intent = new Intent();    	
		intent.setClassName("com.lge.music", "com.lge.music.MusicPicker");
        intent.setAction(Intent.ACTION_GET_CONTENT); 
        intent.putExtra(Drm.EXTRA_CONTENT_ACTION , Drm.CONTENT_ACT_FORWARD);
        startActivityForResult(intent, mMusicRqCode);
        
    } //End Of Method 
    
    /**
     * Handling Vibration click event
     */
	private void event_vibTopGroup() {
		String vib = settingHaving.get("vib");
    	    
    	if (vib == null || "Off".equalsIgnoreCase(vib) || "".equals(vib.trim())) {
    		vibYN.setChecked(true);
    		settingHaving.put("vib", "On");
    	} else if ("On".equalsIgnoreCase(vib)) {
    		vibYN.setChecked(false);
    		settingHaving.put("vib", "Off");
    	}
	}
	
	/**
	 * Handling Puzzle lock click event
	 * if Puzzle lock is checked, Puzzle Alarm will be triggered
	 */
	private void event_puzzleTopGroup() {
		String puzzle =	settingHaving.get("puzzle");
    	if (puzzle == null || "Off".equalsIgnoreCase(puzzle) || "".equals(puzzle.trim())) {
    		puzzleYN.setChecked(true);
    		settingHaving.put("puzzle", "On");
    	}else if ("On".equalsIgnoreCase(puzzle)) {
    		puzzleYN.setChecked(false);
    		settingHaving.put("puzzle", "Off");
    	}
	}
	
	/**
	 * Hide softkeyboard if it is shown when this activity's status changes to onPause
	 * or other click events ( event_puzzleTopGroup, .. etc ) happens
	 */
    private void hideSoftKeyboard()	{
        //Hide soft keyboard, if visible
        //status_text_input_mode = false;
        //mImm.hideSoftInputFromWindow(memoInput.getWindowToken(), 0, new SoftInputResultReceiver());
    	
		mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		if (mImm != null && memoInput != null && mImm.isActive(memoInput)) {
			mImm.hideSoftInputFromWindow(memoInput.getWindowToken(), 0);
			mImm = null;
		}

    }
	
    /**
     * Shows softkeyboard when Memo input is clicked
     * or in onResume() if needed ( ex) Memo touch -> input some characters -> 
     * home button press -> onResume )  
     */
	private void toggleSoftKeyboard() {
		
		//[haesun.jung] 2012.02.17 WBT Null check.
		if ( mImm != null && memoInput != null) {
		    //mImm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
		    mImm.toggleSoftInputFromWindow(memoInput.getWindowToken(), InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
		}
	}
	
	private Handler mToggleSoftKeyboardHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (mImm != null && memoInput != null) {
				mImm.toggleSoftInputFromWindow(memoInput.getWindowToken(),InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);
			}
			super.handleMessage(msg);
		}
	};
	
	/**
	 * Handling Memo click event
	 */
	public void event_memoTopGroup()
	{
		memoInput.setFocusableInTouchMode(true); //seungchul.kang@lge.com
		memoInput.setFocusable(true);
		memoInput.requestFocus();
		
		//InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		//mgr.showSoftInput(memoInput, .SHOW_IMPLICIT);
		//showSoftKeyboard(true);
		mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//		toggleSoftKeyboard();
		mToggleSoftKeyboardHandler.sendMessageDelayed(mToggleSoftKeyboardHandler.obtainMessage(), 100);
	}
	
	/**
	 * @param savedInstanceState Bundle
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		Log.i(TAG, "onCreate");
		
//		Window w = this.getWindow();
//		w.setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
//		         WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
		setContentView(R.layout.alarm_setting);	   

		/* I3.0 Volume Control Code [START] */
		isUseVolumeContorl = CommonUtil.isUseVolumeControl();
		if (isUseVolumeContorl) {
			volume_TopGroup = (LinearLayout) findViewById(R.id.volume_TopGroup);
			if(volume_TopGroup != null)
				volume_TopGroup.setVisibility(View.VISIBLE);
			ImageView imgVolDiv = (ImageView)findViewById(R.id.volume_TopGroup_divider);
			if(imgVolDiv != null)
				imgVolDiv.setVisibility(View.VISIBLE);
		}
		/* I3.0 Volume Control Code [END] */		
		
		//this.setTitle( this.getText(R.string.set_alarm).toString() );
		this.setTitle( this.getText(R.string.STR_set_alarm_NORMAL).toString() );//p930_TD#17933 Set Alarm -> Set alarm

		memoFullToast = Toast.makeText(ALSettings.this, getText(R.string.sp_no_more_letters_NORMAL) , Toast.LENGTH_SHORT);

		resolver = getContentResolver(); 
		res = getResources();  

		// LGE_CHANGE_S : sungtan.back 2011. 2. 11.
		// Block for generality
		/*
		if(eMMCReceiver.isScannerRunning()==true)
        {
        	Log.e("essin","eMMC");
            Toast.makeText(this,  R.string.media_scanner_running, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
		
		registerExternalStorageListener();
		*/
		// LGE_CHANGE_E : sungtan.back 2011. 2. 11.
        
        tbLayout = (SUIToggleButtonGroup)findViewById(R.id.lgdemo_layout_toggle_button_group);

		Intent iSettings = getIntent();
		
		if (iSettings != null && iSettings.getAction() != null && iSettings.getAction().equals("UPDATE")) {
			mAlalrmID = iSettings.getStringExtra( AlarmMeta.COLUMNS.ALARM_ID );
			settingHaving.put(AlarmMeta.COLUMNS.ALARM_HOUR, iSettings.getStringExtra(AlarmMeta.COLUMNS.ALARM_HOUR));
			settingHaving.put(AlarmMeta.COLUMNS.ALARM_MINUTES, iSettings.getStringExtra(AlarmMeta.COLUMNS.ALARM_MINUTES));
			setDaysofweek(iSettings.getIntExtra(AlarmMeta.COLUMNS.ALARM_DAYSOFWEEK, 0));
			settingHaving.put(AlarmMeta.COLUMNS.ALARM_SNOOZE, iSettings.getStringExtra(AlarmMeta.COLUMNS.ALARM_SNOOZE));
			settingHaving.put(AlarmMeta.COLUMNS.ALARM_TONE, iSettings.getStringExtra(AlarmMeta.COLUMNS.ALARM_TONE));
			settingHaving.put(AlarmMeta.COLUMNS.ALARM_VIB, iSettings.getStringExtra(AlarmMeta.COLUMNS.ALARM_VIB));
			settingHaving.put(AlarmMeta.COLUMNS.ALARM_ENABLED, iSettings.getStringExtra(AlarmMeta.COLUMNS.ALARM_ENABLED));
			settingHaving.put(AlarmMeta.COLUMNS.ALARM_MEMO, iSettings.getStringExtra(AlarmMeta.COLUMNS.ALARM_MEMO));
			settingHaving.put(AlarmMeta.COLUMNS.ALARM_PUZZLE, iSettings.getStringExtra(AlarmMeta.COLUMNS.ALARM_PUZZLE));
/* I3.0 Volume Control Code [START] */
			if(isUseVolumeContorl){
				settingHaving.put(AlarmMeta.COLUMNS.ALARM_VOLUME,iSettings.getStringExtra(AlarmMeta.COLUMNS.ALARM_VOLUME));
			}
/* I3.0 Volume Control Code [END] */
		} else {
	        final Calendar mCalendar = Calendar.getInstance();
	        int minutes	= mCalendar.get(Calendar.MINUTE);
	        int hour = mCalendar.get(Calendar.HOUR_OF_DAY);
	        
	        mAlalrmID = "INSERT";
	        settingHaving.put(AlarmMeta.COLUMNS.ALARM_HOUR,			Integer.toString(hour));
	        settingHaving.put(AlarmMeta.COLUMNS.ALARM_MINUTES,		Integer.toString(minutes));	
	        settingHaving.put(AlarmMeta.COLUMNS.ALARM_SNOOZE,		"5");
	        
	        MediaInfoHolder mediaInfor = CommonUtil.getDefaultRingToneInfo(this, AlarmDBQueryCondition.SET_ALARM);
	        settingHaving.put(AlarmMeta.COLUMNS.ALARM_TONE,			mediaInfor.mediaURI == null ? null : mediaInfor.mediaURI.toString());
	        settingHaving.put(AlarmMeta.COLUMNS.ALARM_VIB,			"On");
	        settingHaving.put(AlarmMeta.COLUMNS.ALARM_PUZZLE,		"Off");
	        
/* I3.0 Volume Control Code [START] */			
			if(isUseVolumeContorl){
		        audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);	
				maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
				resetVolume = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
				settingHaving.put(AlarmMeta.COLUMNS.ALARM_VOLUME, 		Integer.toString(maxVolume));
			}	        
/* I3.0 Volume Control Code [END] */
	        
	        settingHaving.put(AlarmMeta.COLUMNS.ALARM_MEMO,			"");
	        settingHaving.put(AlarmMeta.COLUMNS.ALARM_WIDGET_YN,	"N");
	        for( int i = 0; i < ALSettings.yoil.length; i++ ) {
	            ALSettings.yoil[i] = 0;
	        }
		}
		
		mIntHour = Integer.parseInt(settingHaving.get("hour"));
		mIntMinutes = Integer.parseInt(settingHaving.get("minutes"));
		Log.d(TAG, "ALSettings -> set Time! hour : "+mIntHour+", minutes : "+mIntMinutes);
		
        settingDayofWeek();
		
		create_checker = true;
		String uri = settingHaving.get("tone");
		initialUri = uri;
		initialDaysofweek = checkDaysofweek();
	}
	
	private void setDaysofweek(int mDays) {
		/* count selected days */
		int dayCount = 0, days = mDays;
        while (days > 0) {
        	if ((days & 1) == 1) dayCount++;
            days >>= 1;
        }
  
        /* selected days */
        for (int i = 0; i < 7; i++) {
            if ((mDays & (1 << i)) != 0) {  
                ALSettings.yoil[i] = 1;
                dayCount -= 1;;
            } else {
            	ALSettings.yoil[i] = 0;
            }               	
        }
	}	

    /**
     * Field toastForEmmcThread.
     */
    Runnable toastForEmmcThread = new Runnable() {
        public void run() {
            if (sToastTextForEmmc == 1) {
                Toast.makeText(ALSettings.this, R.string.media_scanner_EJECTED, Toast.LENGTH_SHORT).show();
            }else if (sToastTextForEmmc == 2) {
                Toast.makeText(ALSettings.this,  R.string.media_scanner_running, Toast.LENGTH_SHORT).show();
            }
        };
    };

    /**
     * Method onSaveInstanceState.
     * @param state Bundle
     */
    @Override
    protected void onSaveInstanceState(Bundle state) {
 //       super.onSaveInstanceState(state);
        Log.d(TAG, "ALSettings - onSaveInstanceState() [START]");
        state.putString("ALARM_SETTINGS_HOURS", settingHaving.get("hour"));
        state.putString("ALARM_SETTINGS_MINUTES", settingHaving.get("minutes"));
        state.putInt("ALARM_SETTINGS_DAYOFWEEK", checkDaysofweek());
        state.putString("ALARM_SETTINGS_SNOOZE", settingHaving.get("snooze"));
        state.putString("ALARM_SETTINGS_VIB", settingHaving.get("vib"));
        state.putString("ALARM_SETTINGS_TONE", settingHaving.get("tone"));
        state.putString("ALARM_SETTINGS_PUZZLE", settingHaving.get("puzzle"));
        state.putString("ALARM_SETTINGS_MEMO", memoInput.getText().toString());
        Log.d(TAG, "ALSettings - onSaveInstanceState() [END]");
    }
    
    /**
     * Method onRestoreInstanceState.
     * @param state Bundle
     */
    @Override
    protected void onRestoreInstanceState(Bundle state) {
 //       super.onRestoreInstanceState(state);
        Log.d(TAG, "ALSettings - onRestoreInstanceState() [START]");
        ALSettings.settingHaving.put("hour", state.getString("ALARM_SETTINGS_HOURS"));
        ALSettings.settingHaving.put("minutes", state.getString("ALARM_SETTINGS_MINUTES"));
        setDaysofweek(state.getInt("ALARM_SETTINGS_DAYOFWEEK"));
        settingDayofWeek();
        ALSettings.settingHaving.put("snooze", state.getString("ALARM_SETTINGS_SNOOZE"));
        ALSettings.settingHaving.put("vib", state.getString("ALARM_SETTINGS_VIB"));
        ALSettings.settingHaving.put("tone", state.getString("ALARM_SETTINGS_TONE"));
        ALSettings.settingHaving.put("puzzle", state.getString("ALARM_SETTINGS_PUZZLE"));
        ALSettings.settingHaving.put("memo", state.getString("ALARM_SETTINGS_MEMO"));
        Log.d(TAG, "ALSettings - onRestoreInstanceState() [END]");
    }    
// 20100911_mhkwon_SE7839_Save Hour and minutes. ]]
    
    /**
     * Check/uncheck repeated days to ToggleButtons  
     * used in onCreate()
     */
	private void settingDayofWeek() {
	    for ( int i = 0; i < 7; i++ ) {
	        ToggleButton btn = (ToggleButton)tbLayout.getChildAt(i);
	        
	        // [haesun.jung][WBT 325975] 2012.03.09
	        if(btn != null){
	        	boolean bChecked = false;
	        	
	        	if(CommonUtil.isHebrewLanguage()){

	        		if(i == 0){
	        			bChecked = (yoil[6] == 0) ? false : true;
	        		}else{
	        			bChecked = (yoil[i-1] == 0) ? false : true;
	        		}
	        	}else{
	        		 bChecked = (yoil[i] == 0) ? false : true;
	        	}
	        	btn.setChecked(bChecked);
	        }
	    }
	}
	
	private static final String[] MEDIA_EXTERNAL_COLUMNS = new String[] {
 	   	     android.provider.BaseColumns._ID, 
 	   	     android.provider.MediaStore.MediaColumns.TITLE,
 	   	     "\"" + MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "\"",
 	   	     android.provider.MediaStore.Audio.AudioColumns.TITLE_KEY
   	};
	
	private static final String[] MEDIA_INTERNAL_COLUMNS = new String[] {
				android.provider.BaseColumns._ID,
				android.provider.MediaStore.MediaColumns.TITLE,
				"\"" + MediaStore.Audio.Media.INTERNAL_CONTENT_URI + "\"",
				android.provider.MediaStore.Audio.AudioColumns.TITLE_KEY  
	};
	
	/**
	 * suein1209.kim
	 * Check Silent mode
	 * @return
	 */
	private boolean isSilentMode(String uri){
		if (uri == null || uri.equalsIgnoreCase("Off") || "".equals(uri.trim())) {
			return true;
		}else{
			return false;
		} //End Of if
	} //End Of Method isSilentMode
	
	/**
	 * Method onResume.
	 */
	@Override
	protected void onResume() 
	{
		super.onResume();
		
		// [minjoong.park][1443] 2011.10.17. START
		CommonUtil.STOP_DIALOG_REDUNDANCY = true;
		// [minjoong.park][1443] 2011.10.17. END
		
		Log.d(TAG, "===== onResume ==========");
		init();
		//settingTime();
		//settingDayofWeek();
		//////////////////////////////////////////////////////////////
		
		CharSequence[] snooze_kinds = res.getTextArray(R.array.STR_Clock_SELECTSNOOZEKINDS_NORMAL);
			   
		String snooze =	settingHaving.get("snooze");
		Log.d(TAG, "snooze : " + snooze);
		
		if ( snooze == null ) {
			snooze = "0";
		}
		
		int snoozeInt =	Integer.parseInt(snooze);
/* LGSI_CHANGE_S:Alarmclock
 * 2012.03.28,ganesh.kumar@lge.com
 * Default Snooze duration coming wrong for Arab
 */
		/* if ( "".equals(snooze.trim()) || "0".equals(snooze) || "Off".equals(snooze)) {    
			snoozeWriting.setText(snooze_kinds[0]);
		} 
		else if (snoozeInt < 60) {
			for (int i = 0; i < snooze_kinds.length; i++) {
				if ( ((String)snooze_kinds[i]).indexOf(snooze) >= 0 ) {
					Log.d(TAG, "i : " + i);
					snoozeWriting.setText(snooze_kinds[i]);
					break;
				}
			}
		} else if (snoozeInt == 60) {
			snoozeWriting.setText(snooze_kinds[7]);
		} */
	if ( "".equals(snooze.trim()) || "0".equals(snooze) || "Off".equals(snooze)) 
		{    
			snoozeWriting.setText(snooze_kinds[0]);
			Log.d(TAG, "snooze 0 : " + snooze_kinds[0]);
		}
		else if (snoozeInt ==  5)
		{
			snoozeWriting.setText(snooze_kinds[1]);
			Log.d(TAG, "snooze 1 : " + snooze_kinds[1]);
		}
		else if (snoozeInt == 10) {
			snoozeWriting.setText(snooze_kinds[2]);
			Log.d(TAG, "snooze 2 : " + snooze_kinds[2]);
		}
		else if (snoozeInt == 15) {
			snoozeWriting.setText(snooze_kinds[3]);
			Log.d(TAG, "snooze 3 : " + snooze_kinds[3]);
		}
		else if (snoozeInt == 20) {
			snoozeWriting.setText(snooze_kinds[4]);
			Log.d(TAG, "snooze 4 : " + snooze_kinds[4]);
		}
		else if (snoozeInt == 25) {
			snoozeWriting.setText(snooze_kinds[5]);
			Log.d(TAG, "snooze 5 : " + snooze_kinds[5]);
		}
		else if (snoozeInt == 30) {
			snoozeWriting.setText(snooze_kinds[6]);
			Log.d(TAG, "snooze 6 : " + snooze_kinds[6]);
		}
		else if (snoozeInt == 60) {
			snoozeWriting.setText(snooze_kinds[7]);
			Log.d(TAG, "snooze 7 : " + snooze_kinds[7]);
		}
/* LGSI_CHANGE_E:Alarmclock */
		
		String uri = settingHaving.get("tone");
		
		CharSequence title = "N/A";
		if(isSilentMode(uri)){
			title = getText(R.string.silent_alarm_summary);
			Settings.System.putString(resolver, Settings.System.ALARM_ALERT, null);
			
		}else{
			AlarmDBQueryCondition queryCtn = CommonUtil.getBuildOperator() == OPERATOR.DCM  ? AlarmDBQueryCondition.NO_CONDITION : AlarmDBQueryCondition.SET_ALARM; 
			
			MediaInfoHolder infoHolder = CommonUtil.getFinededDefaultTone(this, uri, queryCtn, PrefreParent.ALARM);
			if(infoHolder.mediaLocation == MediaLocation.NO_WHERE){
				
				/*find default ring tone*/
				MediaInfoHolder defaultHolder = getDefaultRingToneInfo(this, queryCtn);
				if(defaultHolder.mediaURI != null){
					title = defaultHolder.mediaTitle;
					uri = defaultHolder.mediaURI.toString();
					
					settingHaving.put("tone", uri);
					Settings.System.putString(resolver, Settings.System.ALARM_ALERT, uri);
				} //End Of if
				
			}else{
				title = infoHolder.mediaTitle;
				uri = infoHolder.mediaURI != null ? infoHolder.mediaURI.toString() : null;
				settingHaving.put("tone", uri);
				Settings.System.putString(resolver, Settings.System.ALARM_ALERT, uri);
			}//End Of if
			
		} //End Of if(isSilentMode(uri))
		if(toneWriting == null) {
			toneWriting  = (TextView)findViewById(R.id.tone_sub);
		}
		toneWriting.setText(title);
		
		
		
		//toneWriting.setText(
//		//String predic = buildModel == BuildMode.L_DOCOMO ? null : "is_alarm = 1";
//		
//		String uri = settingHaving.get("tone");
//
//		if (uri == null || "".equals(uri.trim()) || "Off".equalsIgnoreCase(uri.trim()) ) {
//			Log.d(TAG, "uri == null, '', 'Off'");
//			toneWriting.setText(  this.getText(R.string.silent_alarm_summary).toString() );
//		}else{
//			Log.d(TAG, "uri has value " + uri);
//			
//			/*2012.03.09 suein1209.kim*/
//			String predic = buildModel == BuildMode.L_DOCOMO ? null : "is_alarm = 1";
//			
//			if (uri.indexOf("content://media/external") >= 0) {
//				//if (uri.indexOf("content://settings") >= 0) {		
//				Log.d(TAG, "uri points to external storage");
//
//				Cursor cur = null;
//					try {
//						cur = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, MEDIA_EXTERNAL_COLUMNS, predic, null, "_id");
//
//						if (cur == null) {
//							Log.d(TAG, "external cursor == null");
//							legalToneSetting();
//						} 
//						else {
//
//							Log.d(TAG, "external cur.getcount() : " + cur.getCount());
//							if ( cur.moveToFirst() ) {
//								Log.d(TAG, "external cur.moveToFirst()");
//								boolean find_alarm_tone = false;
//								do {
//									Uri uri1 = ContentUris.withAppendedId(Uri.parse(cur.getString(2)), cur.getLong(0));
//									if ( uri1.toString().equalsIgnoreCase(uri) ) {
//										RingtoneManager mRingtoneManager = new RingtoneManager(this);
//										if(null==mRingtoneManager.getRingtone(this,uri1) ) {
//											
//											toneWriting.setText(defaultRingtoneTitle());
//											ALSettings.settingHaving.put("tone", defaultRingtone());
//											Log.e(TAG, "uri is not correct");
//										}else{
//											toneWriting.setText(  cur.getString(1) );
//											Log.e(TAG, "external find uri" + cur.getString(1));
//											find_alarm_tone = true;
//										}
//										break;
//									}
//								} while (cur.moveToNext());
//
//								if (find_alarm_tone == false) {
//									Log.d(TAG, "external uri can't be found");
//									ALSettings.settingHaving.put("tone", defaultRingtone()); //20110121 taekyeong.yoon 
//									uri = settingHaving.get("tone");
//
//									Cursor ex_fail_cur = null;
//									try {
//										ex_fail_cur = resolver.query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, MEDIA_INTERNAL_COLUMNS,
//												predic,  null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
//										if (ex_fail_cur != null && ex_fail_cur.moveToFirst() ) {//[hyunjung78.park] 2011.08.09 cursor null check
//											Log.d(TAG, "ex_fail_cur.moveToFirst()");
//											toneWriting.setText(  this.getText(R.string.silent_alarm_summary).toString() );
//											do {  
//												Uri uri1 = ContentUris.withAppendedId(Uri.parse(ex_fail_cur.getString(2)), ex_fail_cur.getLong(0));
//												Log.d(TAG, "ex_fail_uri1 = " + uri1.toString());
//												if (uri1.toString().equalsIgnoreCase(uri) ) {
//													toneWriting.setText(  ex_fail_cur.getString(1) );
//													Log.e(TAG, "ex_fail_uri1 set" + ex_fail_cur.getString(1));
//													break;
//												}
//											} while (ex_fail_cur.moveToNext());
//											Log.d(TAG, "ex_fail_cur End While");
//										}
//									} catch (Exception e) {
//										e.printStackTrace();
//									} finally {
//										if (ex_fail_cur != null)
//											ex_fail_cur.close();
//									}
//								}
//							}
//							else {
//								Log.e(TAG, "external cur.moveToFirst() ELSE");
//
//								ALSettings.settingHaving.put("tone", defaultRingtone());//20110121 taekyeong.yoon 
//								uri = settingHaving.get("tone");
//
//								Log.v(TAG, "set defaultRingtone : " + uri);
//
//								Cursor ex_fail_cur = null;
//								try {
//									ex_fail_cur = resolver.query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, MEDIA_INTERNAL_COLUMNS,
//											predic,  null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
//									if (ex_fail_cur != null && ex_fail_cur.moveToFirst() ) {//[hyunjung78.park] 2011.08.09 cursor null check
//										Log.d(TAG, "ex_fail_cur.moveToFirst()");
//										do {  
//											Uri uri1 = ContentUris.withAppendedId(Uri.parse(ex_fail_cur.getString(2)), ex_fail_cur.getLong(0));
//											Log.d(TAG, "uri1 = " + uri1.toString());
//											if (uri1.toString().equalsIgnoreCase(uri) ) {
//												toneWriting.setText(  ex_fail_cur.getString(1) );
//												Log.e(TAG, "match with default ringtone" + ex_fail_cur.getString(1));
//												break;
//											}
//										} while ( ex_fail_cur.moveToNext() );
//										Log.d(TAG,"ex_fail_cur End While");
//									}
//								} catch (Exception e) {
//									e.printStackTrace();
//								} finally {
//									if (ex_fail_cur != null)
//										ex_fail_cur.close();
//								}
//							}
//						}    
//					} catch (Exception e) {
//						e.printStackTrace();
//					} finally {
//						if (cur != null)
//							cur.close();
//					}
//
//			} ////////////////////////////////////////////////////////////////////////////////
//			else {       
//				Log.d(TAG, "uri points to internal storage");
//
//    		 	Cursor cur = null;
//				try {
//					cur = resolver.query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, MEDIA_INTERNAL_COLUMNS,
//							predic,  null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
//	    		 	if (cur != null && cur.moveToFirst()){//[hyunjung78.park] 2011.08.09 cursor null check
//						boolean find_alarm_tone = false;//P930_TD#13093_20110711  Fixed alarm tone name by hyunjung78.park 
//    	    	         do {  
//    	    	        	Uri uri1 = ContentUris.withAppendedId(Uri.parse(cur.getString(2)), cur.getLong(0));
//    	    	        	if (uri1.toString().equalsIgnoreCase(uri) ) {
//    	    	        		toneWriting.setText( cur.getString(1) );
//    	    	        		Log.d(TAG, "match with internal uri" + cur.getString(1));
//								find_alarm_tone = true;//P930_TD#13093  Fixed alarm tone name  by hyunjung78.park 
//	  	    	        		break;
//	  	    	        	}
//    	    	         } while (cur.moveToNext());
//						  //[START]P930_TD#13093_20110711  Fixed alarm tone name displayed "Off" when ringdroid alarm bell set and delete by hyunjung78.park 
//						  if (find_alarm_tone == false) {
//							toneWriting.setText(defaultRingtoneTitle());
//                            ALSettings.settingHaving.put("tone", defaultRingtone()); //20110121 taekyeong.yoon 
//					  	  }
//						  //[END]P930_TD#13093_20110711  Fixed alarm tone name displayed "Off" when ringdroid alarm bell set and delete by hyunjung78.park 
//    	    	 	}
//				} catch ( Exception e ) {
//					e.printStackTrace();
//				} finally {
//					if ( cur != null )
//						cur.close();
//				}
//    		}
//    	} //===else close==
	    		 	
		//////////////////////////////////////////////////
		String vib = settingHaving.get("vib"); 
		Log.d(TAG, "vib : " + vib);
		if( vib == null || "Off".equals(vib) || "".equals(vib.trim()) ) {
			vibYN.setChecked(false);
		} else {
			vibYN.setChecked(true);
		}    
	   
		String puzzle =	settingHaving.get("puzzle");
		Log.i(TAG, "puzzle : " + puzzle);
		if( puzzle == null || "Off".equals(puzzle) || "".equals(puzzle.trim()) ) {
			puzzleYN.setChecked(false);
		} else {
			puzzleYN.setChecked(true);
		}
		
/* I3.0 Volume Control Code [START] */
		String alarm_volume = settingHaving.get(AlarmMeta.COLUMNS.ALARM_VOLUME);
/* I3.0 Volume Control Code [END] */
		Log.e(TAG, "status_text_input_mode : " + status_text_input_mode);
		
		
		if ( status_text_input_mode ) {
			//memoInput.setFocusable(true);
			//memoInput.setFocusableInTouchMode(true);
			// [suhyun99.kim][IN][LU5400][51198] 2011.09.03. Keypad is going disappear when press unlockkey issue fix START
			memoInput.setFocusable(true);                    
			memoInput.setFocusableInTouchMode(true);
            memoInput.requestFocus();
            mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//            toggleSoftKeyboard();
            mToggleSoftKeyboardHandler.sendMessageDelayed(mToggleSoftKeyboardHandler.obtainMessage(), 100);
                        // [suhyun99.kim][IN][LU5400][51198] 2011.09.03. Keypad is going disappear when press unlockkey issue fix END
		} else {
			String memo = settingHaving.get("memo"); // seungchul.kang@lge.com
			memoInput.setText(memo);
//			hideSoftKeyboard();
		}
		
		String hour    = settingHaving.get("hour");
		String minutes = settingHaving.get("minutes");
		if ( true == create_checker ) {
			int memoCursor = memoInput.length();
			memoInput.setSelection(memoCursor);
			if( null == puzzle ) {
				puzzle_value = "Off";
			} else {
				puzzle_value = puzzle;
			}
			
			
/* I3.0 Volume Control Code [START] */
			if(isUseVolumeContorl)
				setInitialInfo (snooze, vib, puzzle_value, memoInput.getText().toString(), alarm_volume,  hour, minutes);
			else
/* I3.0 Volume Control Code [END] */
			setInitialInfo (snooze, vib, puzzle_value, memoInput.getText().toString(), hour, minutes);
			
			create_checker = false;
		} else {
			if ( memoInput.length() > 0 ) {
				if( memoInput.length() >= memoLength ) {
					memoInput.setSelection(memoLength);
				}
				
/* I3.0 Volume Control Code [START] */
				if(isUseVolumeContorl)
					setInitialInfo(initialSnooze, initialVib, initialPuzzle, initialMemo, initialAlarmVolume,  initialHour, initialMinutes);
				else
/* I3.0 Volume Control Code [END] */
				setInitialInfo(initialSnooze, initialVib, initialPuzzle, initialMemo, initialHour, initialMinutes);
			}
		}
		
		mPausedState = false;
/* I3.0 Volume Control Code [START] */
		if(isUseVolumeContorl) {
			setVolumeControl();
		}
/* I3.0 Volume Control Code [END] */
	}
	
	private void setVolumeControl(){
		audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);	
		
		maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
		resetVolume = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);

		String strVol = settingHaving.get(AlarmMeta.COLUMNS.ALARM_VOLUME);
		if(strVol == null || Integer.parseInt(strVol) == -1){
			settingHaving.put(AlarmMeta.COLUMNS.ALARM_VOLUME, Integer.toString(maxVolume));		
			currentVolume = maxVolume;
			initialAlarmVolume = settingHaving.get(AlarmMeta.COLUMNS.ALARM_VOLUME);
		}else{
			currentVolume=  Integer.parseInt(settingHaving.get(AlarmMeta.COLUMNS.ALARM_VOLUME));
		}
	
		alarm_volume_bar = (SeekBar) findViewById(R.id.volume_seekbar);
		alarm_volume_bar.setMax(maxVolume);
		alarm_volume_bar.setProgress(currentVolume);				
		context = this;
		alarm_volume_bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			
			public void onStopTrackingTouch(SeekBar seekBar) {
				 try {					
					mp.prepare();
					} catch (IllegalStateException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
			  	ringerModeStreamTypes = Settings.System.getInt(	getContentResolver(),Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
				ALARM_STREAM_TYPE_BIT = 1 << AudioManager.STREAM_ALARM;				 	
				 
				if((audioManager.getRingerMode() != AudioManager.RINGER_MODE_SILENT) && (audioManager.getRingerMode() != AudioManager.RINGER_MODE_VIBRATE)){
						mp.start();				 					 	
					 
				}
			}
			
			public void onStartTrackingTouch(SeekBar seekBar) {				
					mp.reset();
			}
			
			public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
				//Settings.System.putString(resolver, Settings.System.ALARM_ALERT, settingHaving.get("tone") ); 				
				//Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);				
				

					audioManager.setStreamVolume(AudioManager.STREAM_ALARM, arg1, 0);	
					
					settingHaving.put(AlarmMeta.COLUMNS.ALARM_VOLUME, Integer.toString(arg1));
					mp.setAudioStreamType(AudioManager.STREAM_ALARM);
										
					mTone = settingHaving.get("tone");
			
					
						try {
							mp.setDataSource(context, Uri.parse(mTone));
						} catch (IllegalArgumentException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SecurityException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IllegalStateException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
			}
		});	
	}
	
	@Override
	protected void onRestart() {
		super.onRestart();
		Log.i(TAG, "onRestart");
	}

	@Override
	protected void onStart() {
		super.onStart();
		Log.i(TAG, "onStart");
	}

//	private void legalToneSetting() {
//		Log.d(TAG, "===legalToneSetting====");
//		
//		Uri alert = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
//		if (alert == null) {
//			toneWriting.setText(  this.getText(R.string.silent_alarm_summary).toString() );
//			settingHaving.put("tone", "Off");
//			Settings.System.putString(resolver, Settings.System.ALARM_ALERT, null);
//			ContentValues values = new ContentValues(1);
//            values.put("tone", "Off" );
//            resolver.update(ALProvider.CONTENT_ALARMS_URI, values, "_id=" + mAlalrmID, null);
//		} else { 
//			int i = 1;
//			boolean tag = false;
//			String defaulttone = "", title= "";
//			
//			Cursor cur = null;
//			try {
//				cur = resolver.query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, MEDIA_INTERNAL_COLUMNS,
//						"is_alarm = 1",  null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);           
//				if (cur != null && cur.moveToFirst()) {//[hyunjung78.park] 2011.08.09 cursor null check
//					do {           
//						// Get the field values     
//						Uri uri1 = ContentUris.withAppendedId(Uri.parse(cur.getString(2)), cur.getLong(0));
//						if (uri1.toString().equalsIgnoreCase(alert.toString())) {       
//							Settings.System.putString(resolver, Settings.System.ALARM_ALERT, uri1.toString()); 
//							toneWriting.setText(  cur.getString(1)     );
//							settingHaving.put("tone", uri1.toString()  );
//							// [mo2sangbong.lee@lge.com][22105] 2011.08.22. alarm ring tone change issue fix START
//	                        Object status = Environment.getExternalStorageState();
//							if (status.equals(Environment.MEDIA_MOUNTED) ||
//							        status.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
//								ContentValues values = new ContentValues(1);
//								values.put("tone", uri1.toString() );
//								resolver.update(ALProvider.CONTENT_ALARMS_URI, values, "_id=" + mAlalrmID, null);
//	                        }
//							// [mo2sangbong.lee@lge.com][22105] 2011.08.22. alarm ring tone change issue fix END
//							tag = true; 
//							break;   
//						}
//						if (i == 4) {
//							defaulttone = uri1.toString() ;
//							title = cur.getString(1) ;  
//						} 
//						i++;	    	             
//					}
//					while (cur.moveToNext());
//				}
//			} catch (Exception e) {
//				e.printStackTrace();
//			} finally {
//				if ( cur != null ) cur.close();
//			}
//	    	 	        
//			if (tag == false) { 
//				Settings.System.putString(resolver, Settings.System.ALARM_ALERT, defaulttone ); 
//				toneWriting.setText( title );
//				settingHaving.put("tone", defaulttone );
//	             	       
//				ContentValues values = new ContentValues(1);
//				values.put("tone", defaulttone );
//				resolver.update(ALProvider.CONTENT_ALARMS_URI, values, "_id=" + mAlalrmID, null);
//			} 
//		}  
//	}     
	
   /**
    * Method onStop.
    */
   @Override
   protected void onStop() {
	 // TODO Auto-generated method stub
		 super.onStop();
   }   

    //@SuppressWarnings("unchecked")
    /**
     * Method onClick.
     * @param view View
     * @see android.view.View$OnClickListener#onClick(View)
     */
   
    public void onClick(View view) {
		if(bFinish)
			return;
		
        switch ( view.getId() ) {
            case R.id.saveButton :
            	
            	/*[START] 2012.02.02 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #128361*/
                mTimePicker.clearFocus();//[UIComponent3]
            	/*[END] 2012.02.02 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #128361*/
                memoInput.clearFocus();
                // [start][haesun.jung][IN][P860][115567] 2012.01.05 Fixed alarm set time error
                int hour = mTimePicker.getCurrentHour();
                int minute = mTimePicker.getCurrentMinute();
                setTimeAlarm(hour, minute);
                // [end][haesun.jung][IN][P860][115567] 2012.01.05 Fixed alarm set time error
          
                
            	mSaveButton.setEnabled(false);
            	/*[START] 2012.02.24 suein1209.kim OFFICIAL_EVENT.Mobile_12 - Defect #14638*/
            	// [start][suhyun99.kim][IN][P940][40332] 2011.08.15. save butten view fix
//            	mSaveButton.setTextColor(Color.parseColor(getResources().getString(R.color.black_color)));
            	// [end][suhyun99.kim][IN][P940][40332] 2011.08.15. save butten view fix
            	/*[END] 2012.02.24 suein1209.kim OFFICIAL_EVENT.Mobile_12 - Defect #14638*/
                save();
                break;
                
            case R.id.cancelButton :
                finish();
                break;
            	
            case R.id.Snooze_TopGroup :
                memoInput.setFocusable(false);
                event_snoozeTopGroup();
                break;
                
            case R.id.vib_TopGroup :
                memoInput.setFocusable(false);
                event_vibTopGroup();
                break;
                
            case R.id.Tone_TopGroup :
                memoInput.setFocusable(false);
                event_toneTopGroup();
                break;
                
            case R.id.puzzle_TopGroup :
                memoInput.setFocusable(false);
                event_puzzleTopGroup();
                break;
                
            default :
                break;
        }
    }

	@SuppressWarnings("unchecked")
	private void killOnProcess(String strID) {
		Map.Entry<String, AlarmAlert>temp;
        @SuppressWarnings("rawtypes")
		Set ee;
        @SuppressWarnings("rawtypes")
		Iterator ii;
        ee = AlarmAlert.mAlarmSavings.entrySet();
        ii = ee.iterator();
         
        boolean check = false;
        while(ii.hasNext()) {
        	temp = (Map.Entry<String, AlarmAlert>) ii.next();
            if (strID.equals(temp.getKey())) {
            	check = true;
            	break;
            }
        }
        
        if (check == true) {
        	Log.d(TAG, "===Delete==== _id ===>" + strID);
        	AlarmAlert aa = (AlarmAlert)AlarmAlert.mAlarmSavings.get(strID);
        	if (aa == null) {
    	   		return;
    	   	}
        	aa.forceStop();
        	AlarmAlert.mAlarmSavings.remove(strID);
        }
	}

    /**
     * Method getSnoozeIndex.
     * @return int
     */
    public int getSnoozeIndex() {
    	String snooze =	settingHaving.get("snooze");
		if ( snooze == null ) {
			snooze = "0";
		}
		
    	int index = Integer.parseInt(snooze);
    	
    	int returnIndex = 0;
    	switch(index) {
    		case 0 : returnIndex	=	0 ; break;
    		case 5 : returnIndex	=	1 ; break;
    		case 10 : returnIndex	=	2 ; break;
    		case 15 : returnIndex	=	3 ; break;
    		case 20 : returnIndex	=	4 ; break;
    		case 25 : returnIndex	=	5 ; break;
    		case 30 : returnIndex	=	6 ; break;
    		case 60	: returnIndex	=	7 ; break;
    		default : returnIndex   =   0 ; break;
    	}
    	
    	return returnIndex;
    }   

    /**
     * 2012.03.16 suein1209
     * @param mediaInfo
     */
	private void setBackupToneInfoValue(MediaInfoHolder mediaInfo) {
		if(mediaInfo.mediaURI == null) return; 
		
		SharedPreferences prefs = getSharedPreferences(PrefreParent.ALARM.value(), 0);
		SharedPreferences.Editor ed = prefs.edit();
		ed.putString(mediaInfo.mediaURI.toString().trim(), mediaInfo.fileSizeValue +";"+mediaInfo.dateModifiedValue);
		ed.commit();
	} //End Of Method setBackupToneInfoValue
    
    /**
     * Method onActivityResult.
     * @param requestCode int
     * @param resultCode int
     * @param data Intent
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if (requestCode == mAlarmToneRqCode) {
            String toneText = "N/A";
            String setURI = "N/A";
            //toneTopGroup.setFocusable(true);
            //toneTopGroup.setClickable(true);
    		if (data != null && resultCode==RESULT_OK) {
                Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
                
				if (uri == null) {     	
					toneText = this.getText(R.string.silent_alarm_summary).toString();
					setURI = "Off";
				} else {
					
					MediaInfoHolder mediaInfo = CommonUtil.getMediaInfo(resolver, uri, AlarmDBQueryCondition.NO_CONDITION);
					
					setBackupToneInfoValue(mediaInfo);
					
					toneText = mediaInfo.mediaTitle;
					setURI = mediaInfo.mediaURI != null ? mediaInfo.mediaURI.toString() : null;
				} //End Of if
                
				settingHaving.put("tone", setURI);
				if(toneWriting == null) {
        			toneWriting  = (TextView)findViewById(R.id.tone_sub);
        		}
        		toneWriting.setText(toneText);
                
//                if (uri == null) {
//	                toneText = this.getText(R.string.silent_alarm_summary).toString(); // 20100903_mhkwon_TD7447_Change string sinence to silent 
//	        		settingHaving.put("tone", "Off");
//	        		
//                } else if (uri != null) {
//                	toneText = uri.toString();
//                	
//                	//ContentResolver resolver = getContentResolver();
//                	Cursor cur = null;
//                	try {
//						cur = resolver.query(uri, new String[] { "title" }, null, null, null);
//						if (cur != null && cur.moveToFirst()) {//[hyunjung78.park] 2011.08.09 cursor null check
//						    do {  // Get the field values
//						    	toneText = cur.getString(0);     
//						    } while (cur.moveToNext());
//						}
//					} catch (Exception e) {
//						e.printStackTrace();
//					} finally {
//						if ( cur != null )
//							cur.close();
//					}
//                    settingHaving.put("tone", uri.toString());
//                }
    		} //End Of if (data != null && resultCode==RESULT_OK)
                     
//        	if (resultCode==RESULT_OK) {
//				toneWriting.setText(  toneText  );
//        	}

        }else if(requestCode == mMusicRqCode){
        	/*2012.03.09 suein1209.kim*/
        	
        	if (resultCode==RESULT_OK) {
        		Uri uri = data.getData();
        		
        		String []proj = {MediaStore.MediaColumns.TITLE,MediaStore.MediaColumns.DATA};        				
        		//Cursor cursor = managedQuery (uri, proj, null, null, null);
        		
        		CursorLoader cursorLoader = new CursorLoader(
        				this, 
        				uri, 
        				proj, 
        				null, 
        		        null, 
        		        null);
        		
        		/*[START] 2012.03.28 suein1209.kim INTERNAL_TEST.WBT_12 - Defect #329170 */
        		boolean reFlag = false;
        		if(cursorLoader != null){
        			Cursor cursor = cursorLoader.loadInBackground();
        			if(cursor != null){
        				int index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.TITLE); 
                		cursor.moveToFirst(); 
                		String title = cursor.getString(index);
                		settingHaving.put("tone", uri.toString() );
                		if(toneWriting == null) {
                			toneWriting  = (TextView)findViewById(R.id.tone_sub);
                		}
                		toneWriting.setText(title);
        				
        				/*set setting flag*/
        				reFlag = true;
        				
        				cursor.close();
        				
        			} //End Of if
        		} //End Of if
        		
        		if(reFlag == false){
        			/*There is no null point exception*/
        			settingHaving.put("tone", "Off");
        			if(toneWriting == null) {
            			toneWriting  = (TextView)findViewById(R.id.tone_sub);
            		}
        			toneWriting.setText(this.getText(R.string.silent_alarm_summary).toString());
        		} //End of if
        		/*[END] 2012.03.28 suein1209.kim INTERNAL_TEST.WBT_12 - Defect #329170 */

        	} 
//        	else {
//        		settingHaving.put("tone", null);
//        	}
        } //End Of if

    	/*init*/
    	ringtonePickerIntent = null;
    	
    } //End Of Method onActivityResult
    
 // I3.0 Alarm Volume - Start
 	@Override
 	public void onUserInteraction() {
 		if(isUseVolumeContorl){
 			if(mp != null) {
		 		mp.stop();
		 		audioManager.setStreamVolume(AudioManager.STREAM_ALARM, resetVolume, 0);
 			}
 		}
	 		
 		super.onUserInteraction();
 	}
 // I3.0 Alarm Volume - End
    /**
     * Method onPause.
     */
    @Override
    protected void onPause() {
        Log.d(TAG, "==== ALSettings onPause ==============");
        mPausedState = true;
        
        String memoCompare = settingHaving.get("memo");
        //Log.i(TAG, memoCompare);
        String memoTmp = memoInput.getText().toString();
        
        //WBT fix TD#(175002)
        if(memoCompare != null) {
            if(memoCompare.equals(memoTmp)) {
                Log.d(TAG, "memoCompare : SAME");
            } else {
                settingHaving.put("memo", memoTmp);
            }
        } else {
            Log.e(TAG, "memoCompare value is Null");
        }
        
        memoLength = memoInput.getSelectionEnd();
        
        hideSoftKeyboard();
        
        memoInput.removeTextChangedListener(this);
        
/* I3.0 Volume Control Code [START] */
        mp.stop();
/* I3.0 Volume Control Code [END] */

        super.onPause();
    }
	
//    private boolean checkKorea() 
//    {
//		return false;
//    }
    
//    /**
//	 * Find default ringtone~~~`
//	
//	 * @return String
//     */        
//	public String defaultRingtone() {
//		String defaultTone = "";
//	    Uri alert = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
//	    
//		if (alert == null) {
//			defaultTone = "Off";  
//			return defaultTone ;
//		}
//		
//		String temp = defaultRingtoneTitle();
//        Log.d(TAG, "=>" + temp + "<=" );
//		
//	    ContentResolver resolver = getContentResolver();
//	    Cursor cur = null;
//		try {
//			cur = resolver.query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, MEDIA_INTERNAL_COLUMNS,
//		               "is_alarm = 1",  null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER); 
//			if (cur != null && cur.moveToFirst()) {//[hyunjung78.park] 2011.08.09 cursor null check
//				do {  // Get the field values
//					Uri uri1 = ContentUris.withAppendedId(Uri.parse(cur.getString(2)), cur.getLong(0));
//					int aa = (cur.getString(1)).indexOf( temp );
//					if ( aa >=0 ) {
//						Log.d(TAG, temp + " / Title=" +  cur.getString(1)  +   "<==  URI ==>" + uri1.toString());
//						defaultTone	= uri1.toString();	
//						break;
//					}
//				} while (cur.moveToNext());
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			if (cur != null)
//				cur.close();
//		}
//	 	    
//	 	if ("".equals(defaultTone.trim())) {
//	 		defaultTone = "Off";
//	 	}
//	 	      
//	 	Log.d(TAG, "====defaultTone======>" +  defaultTone );
//	 	return defaultTone;
//	}
      
//    private String defaultRingtoneTitle() 
//    {
//    	Uri alert = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
//	    
//    	if (alert != null) {
//    		final Ringtone r = RingtoneManager.getRingtone(this, alert);
//    		if (r != null) {
//            	Log.d(TAG, "=default===> " + r.getTitle(this) );
//            	return r.getTitle(this);  
//            }
//    	}
//    	
//    	return "";
//	}
     
	private Calendar calculateAlarm(int hour, int minute, Alarms.DaysOfWeek daysOfWeek) {
		// start with now
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());

        int nowHour   = c.get(Calendar.HOUR_OF_DAY);
        int nowMinute = c.get(Calendar.MINUTE);

        // if alarm is behind current time, advance one day
        if (hour < nowHour  ||
        		hour == nowHour && minute <= nowMinute) {
        	c.add(Calendar.DAY_OF_YEAR, 1);
        }
        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minute);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);

        int addDays = daysOfWeek.getNextAlarm(c);
        if ( addDays > 0 ) {
        	c.add(Calendar.DAY_OF_WEEK, addDays);
        }
        
        return c;
	}   
	   
	/**
     * format "Alarm set for 2 days 7 hours and 53 minutes from
     * now"
     */
    private String formatToast(Context context, long timeInMillis) {
    	long delta = timeInMillis - System.currentTimeMillis();
        long hours = delta / (1000 * 60 * 60);
        long minutes = delta / (1000 * 60) % 60;
        long days = hours / 24;
        hours = hours % 24;

        String daySeq = (days == 0) ? "" :
                (days == 1) ? context.getString(R.string.day) :
                context.getString(R.string.days, Long.toString(days));

        String minSeq = (minutes == 0) ? "" :
                (minutes == 1) ? context.getString(R.string.minute) :
                context.getString(R.string.minutes, Long.toString(minutes));

        String hourSeq = (hours == 0) ? "" :
                (hours == 1) ? context.getString(R.string.STR_Clock_HOUR_SHORT) :
                context.getString(R.string.hours, Long.toString(hours));

        boolean dispDays = days > 0; 
        boolean dispHour = hours > 0;
        boolean dispMinute = minutes > 0;

        int index = (dispDays ? 1 : 0) |
                    (dispHour ? 2 : 0) |
                    (dispMinute ? 4 : 0);

        String[] formats = context.getResources().getStringArray(R.array.alarm_set);
/* LGSI_CHANGE_S: Alarm
 * 2012.04.13,prajna.dalei@lge.com,
 * Number conversion in Alarm settings
 */
	 	if("ar".equals(Locale.getDefault().getLanguage()) || "fa".equals(Locale.getDefault().getLanguage())){
			return String.format(formats[index], CommonUtil.convertArabFarsiNum(daySeq,false), CommonUtil.convertArabFarsiNum(hourSeq,false), CommonUtil.convertArabFarsiNum(minSeq,false));
		}else {			
        return String.format(formats[index], daySeq, hourSeq, minSeq);
		}
 /* LGSI_CHANGE_E: Alarm*/
    }

	/**
	 * Method onDestroy.
	 */
	@Override
	protected void onDestroy() {
		
		if (mSDCardMountEventReceiver != null) {
			try{
				unregisterReceiver(mSDCardMountEventReceiver);
			}catch(Exception e){
				e.printStackTrace();
			}
            mSDCardMountEventReceiver = null;
        }
// I3.0 Alarm - Music Tone - Start
		mp.stop();
// I3.0 Alarm - Music Tone - End
		super.onDestroy();
		Log.i(TAG, "onDestory");
	}
	
	/**
	 * Method onKeyUp.
	 * @param keyCode int
	 * @param event KeyEvent
	 * @return boolean
	 * @see android.view.KeyEvent$Callback#onKeyUp(int, KeyEvent)
	 */
	@Override
    public boolean onKeyUp(int keyCode, KeyEvent event) { 
		
		if(bFinish)
			return true;
    	switch (keyCode) { 		
			case KeyEvent.KEYCODE_BACK :
			    // [suhyun99.kim][IN][LU5400][47595] 2011.08.30. back key issue fix START
                /*
                if (mImm != null) {
                    hideSoftKeyboard();
                    return true;
                */
                // [suhyun99.kim][IN][LU5400][47595] 2011.08.30. back key issue fix END
				if(mTimePicker!=null && mTimePicker.isFocused())
					mTimePicker.clearFocus(); //[UIComponent3] 

				if (create_checker || compareInitial()) {
					finish();
				}
				else {
					save();
				}
				return true;
				
			default :
				break;
    	}
		return false; 	
	}
	
	@SuppressWarnings("unchecked")
	private void save() {  
		ContentValues values = null;

		Map.Entry<String, String>temp;
    
		if (bAlarmSaved == true) {
			bAlarmSaved = false;
			return;
		}
		bAlarmSaved = true;
		Set ee = settingHaving.entrySet();
		Iterator ii =  ee.iterator();
        values=new ContentValues();
        while( ii.hasNext() ) {
            temp = (Map.Entry<String, String>) ii.next();
            Log.d(TAG, "Key=" + temp.getKey() + "  ,  Value=" + temp.getValue());
            values.put( temp.getKey(), temp.getValue() );
        }
        
        final int daysofweek_Final = checkDaysofweek();
        values.put("daysofweek", 	daysofweek_Final);
        String memoStr = memoInput.getText().toString();
		values.put("memo", memoStr); // seungchul.kang@lge.com
        Log.d(TAG, "ALSettings save()" + mAlalrmID);      
        ContentValues cvalues = null;
		cvalues	= new ContentValues();

		cvalues.put("hour", 		mIntHour);
    	cvalues.put("minutes", 		mIntMinutes);     
		cvalues.put("daysofweek",   daysofweek_Final);
		cvalues.put("enabled", 	    "1"); 
		cvalues.put("stop",  	    "");
		
        if ("INSERT".equals(mAlalrmID) || mAlalrmID.equals("")) {
        	if ("Y".equalsIgnoreCase(ALSettings.settingHaving.get("widget_yn"))) { 
        		values.put("enabled", 	    "1" );         
        		values.put("widget_yn", 	"Y" );
        		//values.put("widget_type", 	ALSettings.settingHaving.get("widget_type") );
        		resolver.insert(ALProvider.CONTENT_ALARMS_URI,	values);
        	} 
        	else {
        		values.put("enabled", 	 "1" );    
        		values.put("widget_yn",  "N" );
        		resolver.insert(ALProvider.CONTENT_ALARMS_URI,	values);
        	}
        	/////////////////////////////////////////////////////////////////////////////
    		int maxID = 0;
    		
    		String[] projection = new String[] { "max(_id) ID" };
    		Cursor cc = null;
    		try {
    			Log.i(TAG, "" + Alarms.CONTENT_ALARMS_URI.toString());
				cc = resolver.query(Alarms.CONTENT_ALARMS_URI, projection, null, null, null);
				if (cc != null) {   //WBT fix td 207876
					if (cc.moveToFirst()) {  
						maxID = cc.getInt(0);
						Log.d(TAG, "MAX ID=>" + maxID);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if ( cc != null )
					cc.close();
			}
       		////////////////////////////////////////////////
    		cvalues.put( "aid",    maxID);
    		cvalues.put( "aindex", 0);
    		cvalues.put( "status", "A");
        	resolver.insert(ALProvider.CONTENT_CALCU_URI, cvalues);
    		if (maxID != 0) {
    			Alarms.enableAlarm(this, maxID, true);
    		}
    		else {
    			Alarms.setNextAlert(this);
    		}
		} 
        else {
			resolver.update(ALProvider.CONTENT_ALARMS_URI,  values, "_id=" + mAlalrmID, null);
			resolver.update(ALProvider.CONTENT_CALCU_URI,  cvalues, "aid=" + mAlalrmID + "  and aindex = 0", null);
			Alarms.enableAlarm(this, Integer.parseInt(mAlalrmID), true);
			NotificationManager nm = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
			nm.cancel( Integer.parseInt(mAlalrmID) );
			resolver.delete(ALProvider.CONTENT_CALCU_URI, "aid=" + mAlalrmID + "  and aindex > 0",  null);
            killOnProcess(mAlalrmID);
		}
        //added by essin@lge.com 2010.1.29
        Handler calcueHandler = new Handler();
        Runnable calcueHandlerThread = new Runnable() {
        	public void run() {
        		String strHour = settingHaving.get("hour");
        		String strMinutes = settingHaving.get("minutes");	
        		
        		int nHour = Integer.parseInt(strHour);
        		int nMin  = Integer.parseInt(strMinutes);
        		Alarms.DaysOfWeek dow = new Alarms.DaysOfWeek(daysofweek_Final);
        		
        		long timeInMillis = calculateAlarm( nHour, nMin, dow).getTimeInMillis();
				
				String toastText = formatToast(ALSettings.this, timeInMillis);
				Log.d(TAG, Long.toString(timeInMillis));
				Log.d(TAG, toastText);
    	        Toast toast = Toast.makeText(ALSettings.this, toastText, Toast.LENGTH_SHORT);
    	        ToastMaster.setToast(toast);
    	        toast.show();
			}
        };
        calcueHandler.postDelayed(calcueHandlerThread, 0);
        finish();
	}
	
	/**
	 * Field hVL.
	 */
	int[]hVL = new int[2];
	/**
	 * Field mVL.
	 */
	int[]mVL = new int[2];
	/**
	 * Field sVL.
	 */
	int[]sVL = new int[2];
	
	
	/**
	 * Method setInitialInfo.
	 * @param snooze String
	 * @param vib String
	 * @param puzzle String
	 * @param memo String
	 * @param hour String
	 * @param minutes String
	 */
	private void setInitialInfo(String snooze, String vib, String puzzle,
			String memo, String alarm_volume, String hour, String minutes) {

		/* I3.0 Volume Control Code [START] */
		initialAlarmVolume = alarm_volume;
		/* I3.0 Volume Control Code [END] */
		
		setInitialInfo(snooze, vib, puzzle, memo, hour, minutes);
	}

	private void setInitialInfo(String snooze, String vib, String puzzle,
			String memo, String hour, String minutes) {

		initialSnooze = snooze;
		initialVib = vib;
		initialPuzzle = puzzle;
		initialHour = hour;
		initialMemo = memo;
		initialMinutes = minutes;
	}
	
	/**
	 * Method compareInitial.
	 * @return boolean
	 */
	public boolean compareInitial() {
		String snooze  = settingHaving.get("snooze");
		String uri     = settingHaving.get("tone");
		String vib     = settingHaving.get("vib");
		String puzzle  = settingHaving.get("puzzle");
		String memo    = memoInput.getText().toString();
/* [I3.0] Code START */
		String alarm_volume = settingHaving.get(AlarmMeta.COLUMNS.ALARM_VOLUME);		
/* [I3.0] Code END */
		String hour    = settingHaving.get("hour");
		String minutes = settingHaving.get("minutes");
		int daysofweek = checkDaysofweek();
		if (null == puzzle) {
			puzzle_comvalue = "Off";
		}
		else {
			puzzle_comvalue = puzzle;
		}
		if (initialSnooze != null && !initialSnooze.equalsIgnoreCase(snooze) || 
			initialUri != null && !initialUri.equalsIgnoreCase(uri) || 
			initialVib != null && !initialVib.equalsIgnoreCase(vib) ||
			initialPuzzle != null && !initialPuzzle.equalsIgnoreCase(puzzle_comvalue) ||
			initialMemo != null && !initialMemo.equalsIgnoreCase(memo) ||
			initialHour != null && !initialHour.equalsIgnoreCase(hour) ||
			initialMinutes != null && !initialMinutes.equalsIgnoreCase(minutes) || 
/* I3.0 Volume Control Code [START] */
			initialAlarmVolume != null && !initialAlarmVolume.equalsIgnoreCase(alarm_volume) ||
/* I3.0 Volume Control Code [END] */			
			initialDaysofweek != daysofweek ) {
			return false;
		} else {
			return true;
		}
	}
	
	/**
	 * Method checkDaysofweek.
	 * @return int
	 */
	public int checkDaysofweek() {
		int daysofweek = 0;
		int nToggleSize = tbLayout.getChildCount();
        for(int i = 0 ; i < nToggleSize; i++) {
        	ToggleButton t = (ToggleButton)tbLayout.getChildAt(i);
        	
        	/*[START] 2012.02.10 suein1209.kim INTERNAL_TEST.WBT_12 - Defect #308148 */
        	if(t == null) return daysofweek;
        	/*[END] 2012.02.10 suein1209.kim INTERNAL_TEST.WBT_12 - Defect #308148 */
        	
        	if((R.id.toggle_button_mo == t.getId()) && t.isChecked()) {
        		daysofweek += 1;
        	}
        	else if((R.id.toggle_button_tu == t.getId()) && t.isChecked()) {
        		daysofweek += 2;
        	}
        	else if((R.id.toggle_button_we == t.getId()) && t.isChecked()) {
        		daysofweek += 4;
        	}
        	else if((R.id.toggle_button_th == t.getId()) && t.isChecked()) {
        		daysofweek += 8;
        	}
        	else if((R.id.toggle_button_fr == t.getId()) && t.isChecked()) {
        		daysofweek += 16;
        	}
        	else if((R.id.toggle_button_sa == t.getId()) && t.isChecked()) {
        		daysofweek += 32;
        	}
        	else if((R.id.toggle_button_su == t.getId()) && t.isChecked()) {
        		daysofweek += 64;
        	}
        }
        
		return daysofweek;
	}

    @Override
    public void onLowMemory() {
        Log.e(TAG, "onLowMemory");
        super.onLowMemory();
    } 
    
    private void setTimeAlarm(int hour, int minute){
        Calendar mCalendar = Calendar.getInstance();
        mCalendar.set(Calendar.HOUR_OF_DAY, hour);
        mCalendar.set(Calendar.MINUTE, minute);
		settingHaving.put("hour",    Integer.toString(mCalendar.get(Calendar.HOUR_OF_DAY)));
		settingHaving.put("minutes", Integer.toString(mCalendar.get(Calendar.MINUTE)));
		mIntHour = hour;
		mIntMinutes = minute;
    }

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		if(memoInput.isFocused() && memoInput.getText().length() >= MEMO_MAX_LENGTH && !memoFullToast.getView().isShown()){
			memoFullToast.show();
		}

	}
	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		bFinish = true;
	}
} 
